<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="请选择公司名称" filterable clearable @change="handleCompanyChange">
          <el-option v-for="item in topUserList" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantId">
        <!-- <el-input v-model="queryParams.merchantName" placeholder="请输入商户name" clearable -->
        <!-- @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.merchantId" placeholder="请选择商户" filterable clearable @keyup.enter.native="handleQuery">
          <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单日期" prop="date">
        <el-date-picker clearable v-model="queryParams.date" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择订单日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建者" prop="creator">
        <el-select v-model="queryParams.creator" placeholder="请选择创建者" filterable clearable @keyup.enter.native="handleQuery">
          <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
        <!-- <el-input v-model="queryParams.creator" placeholder="请输入创建者" clearable @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <!-- <el-form-item label="签名或者拍照上传路径" prop="sign">
        <el-input v-model="queryParams.sign" placeholder="请输入签名或者拍照上传路径" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['admin:order:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['admin:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['admin:order:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['admin:order:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="id" />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <!-- <el-table-column label="商户id" align="center" prop="merchantId" /> -->
      <el-table-column label="商户name" align="center" prop="merchantName" />
      <el-table-column label="订单日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签名或者拍照上传路径" align="center" prop="sign">
        <template slot-scope="scope">
          <img :src="scope.row.sign" alt="签名或者拍照上传路径" style="width: 50px; height: 50px;"
            v-if="scope.row.sign != null" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="是否结算" align="center" prop="isSettlement">
        <template slot-scope="scope">
          <span v-if="scope.row.isSettlement == 0">未结算</span>
          <span v-if="scope.row.isSettlement == 1">已结算</span>
          <span v-if="scope.row.isSettlement == 2">结算中</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="creatorName" />
      <el-table-column label="是否删除" align="center" prop="isDel">
        <template slot-scope="scope">
          <span v-if="scope.row.isDel == 0">未删除</span>
          <span v-if="scope.row.isDel == 1">已删除</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:order:edit']">查看详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUploadSign(scope.row)"
            v-hasPermi="['admin:order:edit']" v-if="scope.row.sign == null">上传签名图片</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['admin:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改销售单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属公司" prop="companyId"  v-if="isAdmin">
          <el-select v-model="form.companyId" filterable @change="handleCompanyChange" placeholder="请选择所属公司" v-if="type == 0">
            <el-option v-for="item in topUserList" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
          <el-input v-model="form.companyId" placeholder="请输入商户id" disabled v-else />
        </el-form-item>
        <!-- <el-form-item label="公司名称" prop="companyName" v-if="isAdmin">
          <el-input v-model="form.companyName" placeholder="请输入所属公司" disabled />
        </el-form-item> -->
        <el-form-item label="商户name" prop="merchantName">
          <el-select v-model="form.merchantId" placeholder="请选择商户name" v-if="type == 0">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-input v-model="form.merchantName" placeholder="请输入商户name" disabled v-else />
        </el-form-item>
        <el-form-item label="订单日期" prop="date" :disabled="title == '修改销售单'">
          <el-date-picker clearable v-if="type == 0" v-model="form.date" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择订单日期">
          </el-date-picker>
          <el-input v-model="form.date" placeholder="请输入订单日期" disabled v-else />
        </el-form-item>
        <el-form-item label="创建者" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建者" disabled v-if="type == 1" />
          <el-select v-model="form.creator" placeholder="请选择创建者"" v-else>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="签名或者拍照上传路径" prop="sign">
          <el-upload action="http://localhost:8080/admin/user/upload"
            :class="{ 'hide': form.sign != null && form.sign != '' }" list-type="picture-card" :limit="1"
            :on-progress="(event, file) => handleProgress(event, file, 'sign')"
            :on-preview="(file) => handlePictureCardPreview(file, 'sign')"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'sign')"
            :on-remove="(file, fileList) => handleRemove(file, fileList, 'sign')">
            <img v-if="form.sign" :src="form.sign" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="详情" prop="detail">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOneGoods"
            v-if="type == 0">新增</el-button>
          <el-table :data="form.detail" style="width: 100%;text-align: center;">
            <el-table-column align="center" label="商品ID" prop="shopId" />
            <el-table-column align="center" label="商品名称" prop="shopName" />
            <el-table-column align="center" label="商品数量" prop="shopNumber" />
            <el-table-column align="center" label="商品规格" prop="shopSpec" />
            <el-table-column align="center" label="商品价格" prop="shopPrice" />
            <el-table-column align="center" label="金额" prop="shopAmount" />
          </el-table>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" v-if="type == 0">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="shopTitle" :visible.sync="openShop" width="800px" append-to-body>
      <el-form ref="form" :model="goods" :rules="rules" label-width="80px">
        <el-form-item label="商品id" prop="shopId" hidden>
          <el-input v-model="form.shopId" placeholder="请输入商品名称" />
          <!-- <el-select v-model="goods.shopId" @change="handleShopIdChange" placeholder="请选择商品名称">
            <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="商品名称" prop="shopName">
          <el-select v-model="goods.shopId" @change="handleShopIdChange" placeholder="请选择商品名称">
            <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品数量" prop="shopNumber">
          <el-input v-model="goods.shopNumber" type="number" @input="handleInputChange" placeholder="请输入商品数量" />
        </el-form-item>
        <el-form-item label="商品规格" prop="shopSpec">
          <el-select v-model="goods.shopSpec" placeholder="请选择商品规格">
            <el-option v-for="item in spec" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="shopPrice">
          <el-input v-model="goods.shopPrice" type="number" @input="handleInputChange" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="金额" prop="shopAmount">
          <el-input v-model="goods.shopAmount" placeholder="请输入金额" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitShopForm">确 定</el-button>
        <el-button @click="cancelShop">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="上传签名图片" :visible.sync="openUploadSign" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="签名或者拍照上传路径" prop="sign">
          <el-upload action="http://localhost:8080/admin/user/upload"
            :class="{ 'hide': form.sign != null && form.sign != '' }" list-type="picture-card" :limit="1"
            :on-progress="(event, file) => handleProgress(event, file, 'sign')"
            :on-preview="(file) => handlePictureCardPreview(file, 'sign')"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'sign')"
            :on-remove="(file, fileList) => handleRemove(file, fileList, 'sign')">
            <img v-if="form.sign" :src="form.sign" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUploadSignForm">确 定</el-button>
        <el-button @click="cancelUploadSign">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { listMerchant } from '@/api/admin/merchant'
import { handlePictureCardPreview, handleRemove, handleAvatarSuccess, handleProgress } from '@/utils/upload'
import { listShop } from '@/api/admin/shop'
import { listUser } from '@/api/admin/user'
import { getOrderDetail, listOrderDetail } from '@/api/admin/orderDetail'
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/admin/order"
import uploadMixin from '@/utils/upload'
import addGoods from './addGoods'
export default {
  name: "Order",
  computed: {
    ...mapGetters(['topUserList', 'bindUserId', 'roles']),
    isAdmin() {
      return this.roles.includes('admin')
    }
  },
  mixins: [uploadMixin, addGoods],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merchantId: null,
        merchantName: null,
        date: null,
        isSettlement: null,
        creator: null,
        isDel: null,
        sign: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      userList: [],
      orderDetailList: [],
      openUploadSign: false,
      detailTitle: '',
      merchantList: [],  //商户数据
      shopList: [],  //商品数据
      type: 0,
    }
  },
  created() {
    this.getList()
    if (!this.isAdmin) {
      this.getMerchantList()
      this.getShopList()
    }
  },
  methods: {
    /** 查询销售单列表 */
    async getList() {
      this.loading = true
      // if(this.userList.length == 0){
      const res = await listUser({
        top: this.bindUserId,
        type: 1,
      })
      // }
      this.userList = res.rows
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.orderList.forEach((item, i) => {
          this.userList.forEach(it => {
            if (item.creator == it.id) {
              this.$set(this.orderList[i], 'creatorName', it.nickname)
            }
          });
          this.topUserList.forEach(it => {
            if (item.companyId == it.id) {
              this.$set(this.orderList[i], 'companyName', it.nickname)
            }
          });
        });

        this.total = response.total
        this.loading = false
      })
    },
    getMerchantList() {
      listMerchant(this.queryParams).then(response => {
        this.merchantList = response.rows
      })
    },
    getShopList() {
      listShop().then(response => {
        this.shopList = response.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        merchantId: null,
        merchantName: null,
        date: null,
        isSettlement: null,
        creator: null,
        isDel: null,
        sign: null,
        detail: [],
        updateTime: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      if (!this.isAdmin) {
        this.form.companyId = this.bindUserId
      }
      this.open = true
      this.type = 0
      this.title = "添加销售单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.userOrder
        this.$set(this.form, 'detail', response.detail)
        this.type = 1
        this.open = true
        this.title = row.merchantName + "   " + row.date + "   " + "订单详情"
      })
    },
    handleDetail(row) {
      this.reset()
      // const id = row.id || this.ids
      // listOrderDetail({
      //   orderId: id,
      // }).then(response => {
      //   this.orderDetailList = response.rows
      //   this.openDetail = true
      //   this.detailTitle = row.merchantName+"   "+row.date+"   "+"订单详情"
      // })
    },
    handleUploadSign(row) {
      this.openUploadSign = true
      this.$set(this.form, 'id', row.id)
    },
    cancelUploadSign() {
      this.$set(this.form, 'sign', null);
      this.openUploadSign = false
    },
    submitUploadSignForm() {
      if (this.form.sign != null && this.form.sign != '') {
        updateOrder(this.form).then(response => {
          this.$message.success('上传成功')
          this.openUploadSign = false
          this.getList()
        })
      }
      // this.openUploadSign = false
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除销售单编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    handleCompanyChange(val) {
      this.queryParams.companyId = val
      this.getMerchantList()
      // this.getShopList()
    },
  }
}
</script>
